package info.motteke.util;


public class NumberPool {

    private static final long MIN_VALUE;
    private static final long MAX_VALUE;

    private static final Byte[] byteCache;
    private static final Character[] charCache;
    private static final Short[] shortCache;
    private static final Integer[] intCache;
    private static final Long[] longCache;

    static {
        MIN_VALUE = Byte.MIN_VALUE;
        MAX_VALUE = Byte.MAX_VALUE;

        int size = (int) (MAX_VALUE - MIN_VALUE + 1);

        byteCache = new Byte[size];
        charCache = new Character[size];
        shortCache = new Short[size];
        intCache = new Integer[size];
        longCache = new Long[size];

        for(int i = 0; i < size; i++){
            long n = MIN_VALUE + i;
            byteCache[i] = new Byte((byte)n);
            charCache[i] = new Character((char)n);
            shortCache[i] = new Short((short)n);
            intCache[i] = new Integer((int)n);
            longCache[i] = new Long(n);
        }
    }

    private static boolean existsCache(long value){
        return !(value < MIN_VALUE || MAX_VALUE < value);
    }

    private static int index(long value){
        return (int)(value - MIN_VALUE);
    }

    public static Boolean booleanValue(boolean value){
        return value ? Boolean.TRUE : Boolean.FALSE;
    }

    public static Byte byteValue(byte value){
        if(existsCache(value)){
            return byteCache[index(value)];
        }else{
            return new Byte(value);
        }
    }

    public static Character charValue(char value){
        if(existsCache(value)){
            return charCache[index(value)];
        }else{
            return new Character(value);
        }
    }

    public static Short shortValue(short value){
        if(existsCache(value)){
            return shortCache[index(value)];
        }else{
            return new Short(value);
        }
    }

    public static Integer intValue(int value){
        if(existsCache(value)){
            return intCache[index(value)];
        }else{
            return new Integer(value);
        }
    }

    public static Long longValue(long value){
        if(existsCache(value)){
            return longCache[index(value)];
        }else{
            return new Long(value);
        }
    }

    public static Float floatValue(float value){
        return new Float(value);
    }

    public static Double floatValue(double value){
        return new Double(value);
    }
}
